package com.ax.associator.store.common.utils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class Base64ToFile {
/*
* 文件转base64
* @param filePath 文件路径
* @Author Mr.G
* */
    public static  String encryptToBase64(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /*
     * 文件转base64
     * @param basePath parent文件路径
     * @Author Mr.G
     * */
    public static String[] getFilePath(String[] base64 ,  String basePath){
             File dir=new File(basePath);
             if(!dir.exists()&&!dir.isDirectory()){
                 dir.mkdirs();
             }
             String[] filePaths=new String[base64.length];
             String fileName=null;
             for(int i=0;i<base64.length;i++){
                fileName=String.valueOf(System.currentTimeMillis()).concat(".jpg");
                filePaths[i]=basePath.concat("//").concat(fileName);
                byte[] bytes=Base64.getDecoder().decode(base64[i]);
                File f=new File(basePath,fileName);
                 try {
                     f.createNewFile();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
                 try {
                     BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(f));
                     bos.write(bytes);
                     bos.flush();
                     bos.close();
                 } catch (Exception e) {
                     e.printStackTrace();
                 }

             }
             return filePaths;

    }
    public static void main(String[] args){

          String base64[]=new String[1];
          base64[0]= Base64ToFile.encryptToBase64("D://1.jpg");
          String path[]=Base64ToFile.getFilePath(base64,"/AUPLOADIMAGE");
          System.out.println(path[0]);

    }
}
